package com.yiwei.zhh.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.zhh.R;
import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.ModifyFaceBean;
import com.yiwei.zhh.api.bean.UploadImageBean;
import com.yiwei.zhh.constant.Const;
import com.yiwei.zhh.constant.FaceBitmap;
import com.yiwei.zhh.event.IdcardFaceEvent;
import com.yiwei.zhh.util.ImageUtil;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.UI;
import com.yiwei.zhh.view.CircularProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-11-22.
 */

public class ChangePhoneFaceActivity extends BaseActivity {

    //    @BindView(R.id.img_photo)
//    ImageView imgPhoto;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private Unbinder unbinder;
    @BindView(R.id.progressBar)
    CircularProgress loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.activity_identity_by_people_two);
        baseInitView(this, "ChangePhoneFaceActivity", Const.ViewType.ACTIVITY);
        unbinder = ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (FaceBitmap.bitmap != null && !FaceBitmap.bitmap.isRecycled()) {
            FaceBitmap.bitmap.recycle();
            FaceBitmap.bitmap = null;
        }
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    private void showLoading(boolean b) {
        if (loading != null) {
            if (b)
                loading.setVisibility(View.VISIBLE);
            else
                loading.setVisibility(View.GONE);
        }
    }

    private void initView() {
        setBackIntent();
        setTitleText("人工认证");
        EventBus.getDefault().register(this);
    }

    /**
     * 获取相机权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void checkPermission() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                Intent localIntent = new Intent(ChangePhoneFaceActivity.this, FaceActivity.class);
                startActivityForResult(localIntent, 100);
            }

            @Override
            public void superReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IdcardFaceEvent event) {
        if (FaceBitmap.bitmap != null) {
//            imgPhoto.setImageBitmap(FaceBitmap.bitmap);
            uploadImg(ImageUtil.Bitmap2StrByBase64_40(FaceBitmap.bitmap));  //上传颜值
        }
    }

    public void updateFace(String url) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        showLoading(true);
        ModifyFaceBean bean = new ModifyFaceBean();
        bean.face_img = url;
        Api.api_service.getModifyFace(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        showLoading(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    ToastUtil.makeText(getApplicationContext(), "刷脸认证成功", Toast.LENGTH_SHORT).show();
                    Intent msgIntent = new Intent(this, ChangPhoneSecActivity.class);
                    msgIntent.putExtra("token", result.token);
                    startActivity(msgIntent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    finish();
                });
    }

    public void uploadImg(String img) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        showLoading(true);
        UploadImageBean bean = new UploadImageBean();
        bean.img = img;
        Api.api_service.uploadImg(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        showLoading(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    photoUrl = result.getUrl();
                    btnSubmit.setText("完成");
                });
    }

    private String photoUrl = "";

    @OnClick({R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_submit:
                if (UI.toString(btnSubmit).equals("去自拍")) {
                    checkPermission();
                } else {
                    updateFace(photoUrl);
                }


                break;
        }
    }
}
